var renderer, camera, scene;
var controls;
//切换控制器
var controlsState = true;

var VrRender; //创建一个双屏渲染器，当处于双屏状态，则使用双屏渲染器进行渲染
var isVR = false
var sound; //重点展位音频
var clock = new THREE.Clock();
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var OrbitAutoRotate = false;

var poiObjects = [];

const radius = 50 // 球体半径

var fov = 75,
	far = 10000,
	near = 0.01;

var texture_placeholder, isUserInteracting = false,
	onMouseDownMouseX = 0,
	onMouseDownMouseY = 0,
	lon = 90,
	onMouseDownLon = 0,
	lat = 0,
	onMouseDownLat = 0,
	phi = 0,
	theta = 0,
	target = new THREE.Vector3(),
	onPointerDownPointerX,
	onPointerDownPointerY,
	onPointerDownLon,
	onPointerDownLat;

var offsetPostion;

var container = document.getElementById("container");

var rotateAngel = IsPC() ? 180 : 90;

function draw() {
	initRender();
	initScene();
	initCamera();
	initControl();
	initModels(0)


	animate();

	$(function() {
		if(navigator.userAgent.match(/mobile/i)) {
		        $("#gyro").show().find("i").click(() => {
		        	$(this).toggleClass("icon-tuoluoyi");
		        	$(this).toggleClass("icon-t3jinyong");
		        	controlsState = !controlsState;
		        	initControl();
		        
		        })
		       }else {
		          $("#gyro").hide();
		       }

	})
	
	window.onresize = onWindowResize;
	window.addEventListener("click", onMouseClick, false);
	window.addEventListener("mousewheel", onDocumentMouseWheel, false);
	document.getElementById("container").addEventListener("touchstart", onDocumentTouchStart, false);
	document.getElementById("container").addEventListener("touchmove", onDocumentTouchMove, false);

	window.addEventListener('load', function() {
		FastClick.attach(document.body);
	}, false);
}

function initRender() {
	renderer = new THREE.WebGLRenderer({
		antialias: true
	});
	renderer.setSize(document.getElementById("container").clientWidth, document.getElementById("container")
		.clientHeight);
	//告诉渲染器需要阴影效果
	// renderer.shadowMap.enabled = true;
	renderer.setPixelRatio(window.devicePixelRatio);
	renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是，没有设置的这个清晰 THREE.PCFShadowMap

	document.getElementById("container").appendChild(renderer.domElement);
	VrRender = new THREE.StereoEffect(renderer);
}

function initCamera() {
	camera = new THREE.PerspectiveCamera(fov, window.innerWidth / window.innerHeight, near, far);
	camera.position.set(-0.1, 0, -0.1);
	camera.target = new THREE.Vector3(radius, 0, 0) // 设置一个对焦点


}

function onDocumentMouseWheel(event) {

	const fov = camera.fov + event.deltaY * 0.05;

	camera.fov = THREE.Math.clamp(fov, 10, 75);

	camera.updateProjectionMatrix();
}

function initScene() {
	scene = new THREE.Scene();
	scene.background = new THREE.Color(0xa0a0a0);
}

function initModels(id) {

	useSphere(roomData[id].selfRoom);
	initPoints(roomData[id].spriteArr);

}


//纹理加载进度
function play(a) {
	document.getElementsByClassName("trends")[0].style.width = a + "%";
	document.getElementsByClassName("mask")[0].textContent = (a - 1) + "%";
	// console.log(a)
	if (a < 100) {
		document.getElementById("progress").style.display = "block";
	} else {
		document.getElementById("progress").style.display = "none";
	}
}

function useSphere(path) {

	poiObjects = [];

	var sphereGeometry = new THREE.SphereGeometry(radius, 32, 32);

	sphereGeometry.scale(1, 1, -1);

	let event = {}
	event.onLoad = () => {
		// console.log('图片加载完成')
	}
	event.onProgress = (texture, num, total) => {

		play((num / total) * 100)
	}

	event.onError = (texture) => {
		Toast('图片加载错误');
	}
	const loadingManager = new THREE.LoadingManager(
		event.onLoad,
		event.onProgress,
		event.onError
	)

	const textureLoader = new THREE.TextureLoader(loadingManager)

	const texture = textureLoader.load(path)

	var sphereMaterial = new THREE.MeshBasicMaterial({
		map: texture
	});


	var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

	var newPath = '';
	if (path.indexOf("/") > 0) {
		filename = path.substring(path.lastIndexOf("/") + 1, path.length);
		newPath = "img/room/" + filename
	}
	//加载高清图
	new THREE.TextureLoader(loadingManager).load(newPath, texture => {
		outside = new THREE.MeshBasicMaterial({
			map: texture
		});
		sphere.material = outside;
	});
	// sphere.material.wireframe  = true; //网格显示
	sphere.name = 'room'
	scene.add(sphere);
}


$(function() {

	$('.icon-VR').click(function() {
		console.log("vr")
		isVR = !isVR;

	})

	$('.icon-quanjingshijiao').click(function() {
		OrbitAutoRotate = !OrbitAutoRotate
		controls.autoRotate = OrbitAutoRotate;
	})

});


function initPoints(hotPointArr) {
	// console.log(hotPointArr)
	for (var i = 0; i < hotPointArr.length; i++) {

		let sprite = createAnimateSprite(hotPointArr[i].matPath, 16, hotPointArr[i]
			.position.x, hotPointArr[i].position.y, hotPointArr[i].position.z, hotPointArr[i].vid,
			hotPointArr[i]
			.name, hotPointArr[i].textContent);

	}

}

function createAnimateSprite(imgUrl, size, x = 0, y = 0, z = 0, vid, name, textContent) {
	return new Promise((resolve, reject) => {
		new THREE.TextureLoader().load(
			imgUrl,
			(texture) => {
				const img = texture.image;
				const height = img?.height;
				const width = img?.width;
				const ratio = width / height || 1;
				const scale = 16 / width;
				texture.wrapS = THREE.RepeatWrapping;
				texture.wrapT = THREE.RepeatWrapping;
				texture.repeat.y = ratio;
				const material = new THREE.SpriteMaterial({
					map: texture,
					depthTest: false,
					depthWrite: false,
					sizeAttenuation: false,
					side: THREE.DoubleSide,
					transparent: true,
					opacity: 0.9,
				});
				material.needsUpdate = true;
				const obj = new THREE.Sprite(material);
				obj.scale.set(scale, scale, scale);
				obj.position.x = x;
				obj.position.y = y;
				obj.position.z = z;

				// play animation
				setInterval(() => {
					texture.offset.y -= ratio;
				}, 1000 * ratio);

				resolve(obj);
				obj.vid = vid;
				obj.name = name;
				obj.textContent = textContent;
				scene.add(obj)
				poiObjects.push(obj);
			},
			undefined,
			() => reject()
		);
	});
}

//加载重点展位音频
function addAudio(audioPath, callback) {
	// 创建一个 AudioListener 并将其添加到 camera 中
	const listener = new THREE.AudioListener();
	// camera.add(listener);

	// 创建一个全局 audio 源
	sound = new THREE.Audio(listener);

	// 加载一个 sound 并将其设置为 Audio 对象的缓冲区
	const audioLoader = new THREE.AudioLoader();
	audioLoader.load(audioPath, function(buffer) {
		sound.setBuffer(buffer);
		sound.setLoop(false);
		sound.setVolume(1);
		sound.play();
	});

}

function clearnSprite() {
	for (let i = scene.children.length - 1; i >= 0; i--) {
		if (scene.children[i].type === "Sprite") {
			scene.remove(scene.children[i]);

		}

	}

	scene.remove(scene.getObjectByName("room"));

}



function initControl() {
	if (controlsState) {
		if (controls) {
			controls.dispose()
		}
		controls = new THREE.OrbitControls(camera, renderer.domElement);
		controls.enableRotate = true;
		controls.rotateSpeed = .5;
		//动态阻尼系数 就是鼠标拖拽旋转灵敏度
		controls.dampingFactor = 0.25;
		//是否可以缩放
		controls.enableZoom = false;
		//是否自动旋转
		controls.autoRotate = false;
		controls.autoRotateSpeed = 0.5;
		//设置相机距离原点的最远距离
		controls.minDistance = .1;
		//设置相机距离原点的最远距离
		controls.maxDistance = 400;
		//是否开启右键拖拽
		controls.enablePan = false;

	} else if (controlsState === false) {

		if (controls) {
			controls.dispose()
		}
		controls = new THREE.DeviceOrientationControls(camera);
		controls.connect();
	}

}

function render() {

	controls.update();

	if (isVR) {
		VrRender.render(scene, camera);
	} else {
		//设置渲染器恢复默认状态

		renderer.setSize(window.innerWidth, window.innerHeight);
		renderer.render(scene, camera);
	}
}

function onWindowResize() {

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize(window.innerWidth, window.innerHeight);

}

function animate() {
	//更新控制器
	render();

	requestAnimationFrame(animate);
}

function onMouseClick(event) {

	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

	//将平面坐标系转为世界坐标系
	raycaster.setFromCamera(mouse, camera);

	//得到点击的几何体
	var raycasters = raycaster.intersectObjects(poiObjects, false);
	if (raycasters.length > 0) {

		Toast(raycasters[0].object.name, 2000);

		if (raycasters[0].object.vid) {
			clearnSprite()
			initModels(raycasters[0].object.vid)

			$('.imgNavUl li').removeClass("addLiStyle");
			$(".imgNavUl li").eq(raycasters[0].object.vid).addClass("addLiStyle addLiVisited");
			$('.imgNavUl li p span').removeClass("scroll-text");
			$(".imgNavUl li").eq(raycasters[0].object.vid).find("span").addClass("scroll-text");
		} else {
			console.log(raycasters[0].object);
			let sel = raycasters[0].object;
			$(".mianSceneContentWrap").show();
			$('.mianSceneHead h2').text(sel.textContent.title);
			$('.mianSceneContent p').text(sel.textContent.content);
			if (sel.textContent.audioPath) {
				addAudio(sel.textContent.audioPath)

			}

		}

	}

}

function onDocumentTouchStart(a) {
	a.preventDefault();
	if (a.touches.length == 1) {
		onPointerDownPointerX = a.touches[0].pageX;
		onPointerDownPointerY = a.touches[0].pageY;
		onPointerDownLon = lon;
		onPointerDownLat = lat

		mouse.x = (a.touches[0].pageX / window.innerWidth) * 2 - 1;
		mouse.y = -(a.touches[0].pageY / window.innerHeight) * 2 + 1;

		//将平面坐标系转为世界坐标系
		raycaster.setFromCamera(mouse, camera);

		//得到点击的几何体
		var raycasters = raycaster.intersectObjects(poiObjects, false);
		if (raycasters.length > 0) {

			Toast(raycasters[0].object.name, 2000);

			if (raycasters[0].object.vid) {
				clearnSprite()
				initModels(raycasters[0].object.vid)

				$('.imgNavUl li').removeClass("addLiStyle");
				$(".imgNavUl li").eq(raycasters[0].object.vid).addClass("addLiStyle addLiVisited");
				$('.imgNavUl li p span').removeClass("scroll-text");
				$(".imgNavUl li").eq(raycasters[0].object.vid).find("span").addClass("scroll-text");
			} else {
				console.log(raycasters[0].object);
				let sel = raycasters[0].object;
				$(".mianSceneContentWrap").show();
				$('.mianSceneHead h2').text(sel.textContent.title);
				$('.mianSceneContent p').text(sel.textContent.content);
				if (sel.textContent.audioPath) {
					addAudio(sel.textContent.audioPath)

				}

			}

		}

	} else {
		if (a.touches.length == 2) {
			offsetPostion = getDistance({
				x: a.touches[0].pageX,
				y: a.touches[0].pageY
			}, {
				x: a.touches[1].pageX,
				y: a.touches[1].pageY
			})
		}
	}
}

function onDocumentTouchMove(c) {
	c.preventDefault();
	if (c.touches.length == 1) {

		lon = (onPointerDownPointerX - c.touches[0].pageX) * 0.2 + onPointerDownLon;
		lat = (c.touches[0].pageY - onPointerDownPointerY) * 0.2 + onPointerDownLat
	} else {
		if (c.touches.length == 2) {
			var a = getDistance({
				x: c.touches[0].pageX,
				y: c.touches[0].pageY
			}, {
				x: c.touches[1].pageX,
				y: c.touches[1].pageY
			});
			camera.fov += (offsetPostion - a) * 0.01;
			if (camera.fov > 110) {
				camera.fov = 110
			} else {
				if (camera.fov < 30) {
					camera.fov = 30
				}
			}
			camera.updateProjectionMatrix()
		}
	}
}

function getDistance(d, c) {
	var a = c.x - d.x;
	var b = c.y - d.y;
	return Math.pow((a * a + b * b), 0.5)
}
function IsPC() {
	var a = navigator.userAgent;
	var d = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
	var b = true;
	for (var c = 0; c < d.length; c++) {
		if (a.indexOf(d[c]) > 0) {
			b = false;
			break
		}
	}
	return b
}


window.onload = draw;
